<?php


namespace app\common\model;


use think\Model;

class UserCouponModel extends Model
{
    protected $name = 'user_coupon';

    // 优惠类型
    public static $discount_type = [1 => '满减', 2 => '折扣'];
    // 适用商品:all=全部商品,part=部分商品
    public static $goods_type = ['all' => '全部商品', 'part' => '部分商品'];
    // 使用位置:mini=小程序,pc=PC
    public static $use_type = ['mini' => '小程序', 'pc' => 'PC'];


    /**
     * 个人中心--获取我的优惠券
     *
     * @param $user_id int 用户ID
     * @param $status int 状态:0=全部,1=未使用,2=已使用,3=已失效
     * @param $page int 页码
     * @param $limit int 每页数据
     */
    public function getUserCouponPageList($params,$user_id,$page,$limit)
    {
        extract($params);
        try {

            $field = ['id','discount_type','goods_type','use_type','title','target','price','discount','starttime','endtime','status'];
            $where = [
                'user_id' => $user_id,
            ];
            if($status > 0){
                $where['status'] = $status;
            }

            $list = self::field($field)
                ->where($where)
                ->order('createtime', 'desc')
                ->paginate($limit, false, ['page' => $page]);

//            $discount_type = [1 => '满减', 2 => '折扣'];
//            $goods_type = ['all' => '全部商品', 'part' => '部分商品'];
//            $use_type = ['mini' => '小程序', 'pc' => 'PC'];

            foreach ($list as $row){
                $row->discount_type_text = self::$discount_type[$row->discount_type];
                $row->goods_type_text = self::$goods_type[$row->goods_type];
//                $row->use_type_text = $use_type[$row->use_type];
                $row->starttime = datetime($row->starttime);
                $row->endtime = datetime($row->endtime);
            }

            return [
                'code' => 200,
                'msg' => '请求成功',
                'data' => $list
            ];
        }catch (\Exception $e) {
            return [
                'code' => $e->getCode(),
                'msg' => $e->getMessage(),
                'data' => []
            ];
        }
    }


    /**
     * 获取可用优惠券
     *
     * @param int $user_id 用户ID
     * @param float $price 价格
     * @param string $use_type 使用位置:mini=小程序,pc=PC
     * @param array $goods_ids 商品ID集
     * @param int $user_coupon_id 用户优惠券ID
     */
    public static function UsableCoupon($user_id, $price, $use_type, $goods_ids, $user_coupon_id)
    {
        $where = [
            'user_id' => $user_id,
            'starttime' => ['<=', time()],
            'endtime' => ['>=', time()],
            'target' => ['<=', $price],
            'status' => 1,
        ];
        $field = ['id as user_coupon_id','discount_type','goods_type','title','target','price','discount','starttime','endtime','status'];
//        $field = ['id as user_coupon_id','title'];

        $FIND_IN_SET = [];
        foreach ($goods_ids as $val){
            $FIND_IN_SET[] = "FIND_IN_SET('$val',`goods_ids`)";
        }
        // 用or是匹配所有符合条件的优惠券
//        $FIND_IN_SET = implode(' or ',$FIND_IN_SET);
        // 用and是锁定单张优惠券必须包含下单的所有商品
        $FIND_IN_SET = implode(' and ',$FIND_IN_SET);

        $FIND_IN_SET .= " OR `goods_type`='all'";

        $list = self::field($field)
            ->where($where)
            ->whereRaw("FIND_IN_SET('$use_type',`use_type`)")
            ->whereRaw($FIND_IN_SET)
            ->select();

        foreach ($list as $row) {
//            $row->user_coupon_id = $row->id;
            $row->starttime = datetime($row->starttime);
            $row->endtime = datetime($row->endtime);
            switch ($row->discount_type){
                case 1:
                    $row->price_text = "￥".$row->price;
                    break;
                case 2:
                    $row->price_text = $row->discount."折";
                    break;
            }
            $row->discount_type_text = "满". $row->target ."可用";
            $row->end_time_text = "有效期至". $row->endtime;
            $row->goods_type_text = self::$goods_type[$row->goods_type];
            $row->is_check = 0;
            if(!empty($user_coupon_id)){
                if($row->user_coupon_id == $user_coupon_id){
                    $row->is_check = 1;
                }
            }
        }

        return $list;
    }

    /**
     * 判断是否可使用优惠券并且获取优惠金额
     *
     * @param int $user_id 用户ID
     * @param float $price 价格
     * @param int $user_coupon_id 用户优惠券ID
     */
    public static function CouponInfo($user_id, $price, $user_coupon_id)
    {
        $data = self::get(['id' => $user_coupon_id,'user_id' => $user_id]);

        if(!$data){
            Exception('未找到优惠券信息',41004);
        }
//        $data = $data->toArray();
        if($data->status == 2){
            Exception('优惠券已使用',41005);
        }
        $time = time();
        if($data->status == 3 || $data->starttime >= $time || $data->endtime <= $time){
            Exception('优惠券已过期',41006);
        }
        if($data->target > $price){
            Exception('不满足门槛金额',41007);
        }
        $couponAllPrice = 0;
        //优惠类型:1=满减,2=折扣
        switch ($data->discount_type) {
            case 1:
                $couponAllPrice = $data->price;
                break;
            case 2:
                $discount = $data->discount / 10;
                $couponAllPrice = $price - ( $price * $discount );
//                $couponAllPrice = $price * $discount;
                $couponAllPrice = round($couponAllPrice, 2);
                break;
        }
        return $couponAllPrice;
    }
}